<template>
  <page-container title="厂房管理" class="container">
    <!--选择产品型号-->
    <div class="action-container">
      <el-select
        v-model="selectedProductType"
        placeholder="请选择产品型号"
        clearable
        filterable
        @change="getChannelList"
        style="width: 200px; margin-right: 20px"
      >
        <el-option
          v-for="item in productTypes"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
    </div>

    <!-- 机台号列表渲染 -->
    <el-table
      v-loading="loading"
      :data="clothList"
      style="width: 100%"
      height="550px"
    >
      <el-table-column type="index" label="序号" width="80"></el-table-column>
      <el-table-column label="机台号" width="250">
        <template #default="scope">
          {{ scope.row.equipmentNo }}
        </template>
      </el-table-column>
      <el-table-column label="在线状态" width="150">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.onlineState === '在线'
                ? 'success'
                : scope.row.onlineState === '离线'
                ? 'danger'
                : 'warning'
            "
            disable-transitions
          >
            {{ scope.row.onlineState }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设置" width="450">
        <template #default="scope">
          <el-button type="primary" size="small" @click.prevent="skip1(scope)">
            相机参数
          </el-button>
          <el-button type="primary" size="small" @click.prevent="skip2(scope)">
            检测开关
          </el-button>
        </template>
      </el-table-column>
      <!-- 没有数据 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <!-- 管理机台 -->
    <el-dialog v-model="dialogVisible" title="管理机台" width="450px">
      <el-form label-width="100px" style="padding-right: 30px">
        <el-form-item label="车间名称">
          <el-select v-model="formModel.id" @click="getWorkShop">
            <el-option
              v-for="channel in workshopList"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机台号">
          <el-input
            v-model="formModel.deviceCode"
            placeholder="请输入机台号"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit"> 确认添加 </el-button>
          <el-button @click="onResetDeviceCode">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loadingdeviceCode"
        style="width: 100%"
        height="350px"
        :data="deciveCodeList"
      >
        <el-table-column
          type="index"
          label="序号"
          width="100px"
        ></el-table-column>
        <el-table-column prop="workShopName" label="车间"></el-table-column>
        <el-table-column prop="deviceCode" label="机台号"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              circle
              plain
              type="danger"
              :icon="Delete"
              @click="deletedeviceCode(row)"
            ></el-button>
          </template>
        </el-table-column>
        <!-- 没有数据 -->
        <template #empty>
          <el-empty description="没有数据"></el-empty>
        </template>
      </el-table>
    </el-dialog>
  </page-container>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useUserStore } from '@/stores'
import { Delete } from '@element-plus/icons-vue'
// import { Edit } from '@element-plus/icons-vue'
// import { placeholderSign } from 'element-plus/es/components/table-v2/src/private'
import {
  deleteDeviceCode,
  getOTAlist,
  getProductType,
  remoteGetEquipmentNumList
} from '@/api/clothrequest'
import { GetWorkShopService } from '@/api/clothrequest'
import { machineAddService } from '@/api/clothrequest'
import { useParms } from '@/stores'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const clothList = ref([])
const loading = ref(false)
const loadingdeviceCode = ref(false)
const dialogVisible = ref(false)
const params = ref({
  factoryId: '',
  id: ''
})
const deciveCodeList = ref([])
const workshopList = ref([])
const useparms = useParms()
useparms.emptyParams()
const selectedProductType = ref('') // 当前选中的型号
const productTypes = ref([]) // 存储产品型号列表
const originalData = ref([]) // 存储全量数据
const OTALoading = ref(false)
// const userStore = useUserStore()
//
// onMounted(async () => {
//   try {
//     await loadProductTypes() // 先加载型号
//     if (selectedProductType.value) {
//       await loadOTAList() // 再加载对应型号的 OTA 数据
//     }
//     await getChannelList()
//   } catch (error) {
//     ElMessage.error('加载失败: ' + error.message)
//   }
// })
onMounted(async () => {
  try {
    // 尝试从本地存储获取保存的型号
    const savedProductType = localStorage.getItem('workshopSelectedProductType')
    if (savedProductType) {
      selectedProductType.value = savedProductType
    }

    await loadProductTypes()
    await getChannelList()
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message)
  }
})

const getChannelList = async () => {
  try {
    loading.value = true

    if (selectedProductType.value) {
      localStorage.setItem('workshopSelectedProductType', selectedProductType.value);
    }
    const res = await remoteGetEquipmentNumList(selectedProductType.value)
    // clothList.value = res.data.data
    console.log(res)
    if (res.data.code === 1) {
      clothList.value = res.data.data
    } else {
      clothList.value = [] // 防止无效数据
    }
  } catch (error) {
    ElMessage.error('获取设备列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const formModel = ref({
  id: '',
  deviceCode: ''
})

const skip1 = (item) => {
  console.log('item.row', item.row)
  router.push({
    path: '/equipment/equipmentSetParameter',
    query: {
      equipment_no: item.row.equipmentNo
    }
  })
}

const skip2 = (item) => {
  console.log('item.row', item.row)
  router.push({
    path: '/equipment/equipmentSwitchDetection',
    query: {
      equipment_no: item.row
    }
  })
}

const onSubmit = async () => {
  await ElMessageBox.confirm('此操作将增加机台号, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  })
  console.log(formModel.value)
  await machineAddService(formModel.value)
  onResetDeviceCode()
  ElMessage.success('添加成功')
}
const getWorkShop = async () => {
  const res = await GetWorkShopService(params.value)
  workshopList.value = res.data.data
}
const deletedeviceCode = async (row) => {
  // 提示用户是否要删除
  await ElMessageBox.confirm(
    '此操作将删除该机台号，正在工作的不能删除, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  )
  await deleteDeviceCode(row)
  ElMessage.success('删除成功')
  // 重新渲染列表
  getdeviceCodeList()
}
const onResetDeviceCode = () => {
  formModel.value.id = ''
  formModel.value.deviceCode = ''
  getdeviceCodeList()
}
const getdeviceCodeList = async () => {
  loadingdeviceCode.value = true
  const res = await remoteGetEquipmentNumList(selectedProductType.value)
  deciveCodeList.value = res.data.data
  loadingdeviceCode.value = false
}

const loadOTAList = async () => {
  try {
    OTALoading.value = true
    if (!selectedProductType.value) {
      originalData.value = []
      return
    }
    const res = await getOTAlist(selectedProductType.value)
    if (res.data?.code === 1) {
      originalData.value = res.data.data
    } else {
      originalData.value = []
      ElMessage.warning(res.data?.message || '数据加载异常')
    }
  } catch (error) {
    originalData.value = []
    ElMessage.error('加载失败: ' + error.message)
    console.error('加载错误详情:', error)
  } finally {
    OTALoading.value = false // 无论成功失败都关闭加载状态
  }
}

// 加载产品型号列表
const loadProductTypes = async () => {
  try {
    const res = await getProductType()
    if (res.data?.code === 1) {
      productTypes.value = res.data.data
      // 如果本地存储中有型号，且该型号在可用列表中，则使用它
      const savedProductType = localStorage.getItem('workshopSelectedProductType');
      if (savedProductType && productTypes.value.includes(savedProductType)) {
        selectedProductType.value = savedProductType;
      } else if (productTypes.value.length > 0) {
        // 否则使用第一个型号
        selectedProductType.value = productTypes.value[0];
      }
    }
  } catch (error) {
    console.error('型号加载失败:', error)
    ElMessage.warning('型号列表加载失败')
  }
}
</script>

<style lang="scss" scoped>
.container {
  border-radius: 20px;
  font-weight: bold;
  font-size: 17px;
}
.add-button {
  background-color: #077aee;
  font-weight: bold;
  color: #fff;
}
.select-button {
  background-color: #077aee;
  color: #fff;
}
.action-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
